
/************************************************************************
*************************************************************************
*************************************************************************
uk_transparency_maintext.do

Replicates tables and figures in main text. Code appears in order of
exhibit (Table 1, Figure 2, ...)

Note that figures that are simple images (eg. Figure 1) are not
reproduced.
*************************************************************************
*************************************************************************
************************************************************************/






/************************************************************************
*************************************************************************
Preparation
*************************************************************************
************************************************************************/

//SET THIS TO POINT TO THE FOLDER CONTAINING THIS FILE
cap cd "D:\Dropbox\projects\jobcardcorruption\analysis\uk_rejres\replication"






do "do/ajayrd.ado"

global bw 15.611
global stars * 0.10 ** 0.05 *** 0.01




cap mkdir ukresults
cap mkdir ukresults/regressions
cap mkdir ukresults/graphs
cap mkdir ukresults/tables




/************************************************************************
*************************************************************************
Table 1
*************************************************************************
************************************************************************/



/************************************************************************
Prepare survey sample for merging
************************************************************************/

use "dta/UK_pradhan_cleaned.dta", clear

rename (_all) svy_=

rename svy_pradhanid pid

//Somi called this person then had to call back, but submitted both forms
drop if pid==2968 & svy_duration < 50

gen rank = 1
tempfile surveyed
save `surveyed'



/************************************************************************
Merge survey sample into main data
************************************************************************/

use "dta/uk_rd_dataset.dta", clear
drop tmp

merge 1:1 pid rank using `surveyed'
/*

    Result                           # of obs.
    -----------------------------------------
    not matched                         1,443
        from master                     1,443  (_merge==1)
        from using                          0  (_merge==2)

    matched                               207  (_merge==3)
    -----------------------------------------
*/



/************************************************************************
Generate variables to summarize
************************************************************************/
gen female 		= gender_candidate == "Female"
gen sct 		= category == "SC" | category == "ST"
gen inbw 		= abs(rvlev) < ${bw}
**# Bookmark #1
gen pradhan 	= rank == 1
gen surveyed 	= _m == 3




/************************************************************************
Calculate summary stats and store in macros
************************************************************************/

gen sampfull = 1
gen sampbw	 = inbw
gen sampwin  = pradhan
gen sampsurv = surveyed

local keylist
foreach sample in full bw win surv {
	preserve
	keep if samp`sample'
	
	foreach var of varlist pradhan female sct inbw surveyed rvlev zndays2015 zndays2013 {
		sum `var'
		local `var'`sample' 	= string(r(mean), "%9.2f")
		local sd`var'`sample' 	= "(" + string(r(sd), "%9.2f") + ")"
		
		local keylist `keylist' `var'`sample' sd`var'`sample'
	}

	count
	local obs`sample' = r(N)

	egen tag = tag(pid)
	count if tag
	local npanch`sample' = r(N)
	
	
	local keylist `keylist' obs`sample' npanch`sample'
	
	restore
}
	
	
	

/************************************************************************
Output table
************************************************************************/
	
//Base file:
tempfile desc0
filefilter "templates/descriptives2.txt" "`desc0'", from(" ") to(" ")

//Loop
local onfile = 0
foreach key in `keylist' {
	local tmp = `onfile'+1
	tempfile desc`tmp'
	filefilter "`desc`onfile''" "`desc`tmp''", from("[`key']") to("``key''")
	local onfile = `tmp'
}

//The last temporary file we made is the final version
copy "`desc`tmp''" "ukresults/tables/descriptives2.tex", replace




/************************************************************************
*************************************************************************
Figure 2
*************************************************************************
************************************************************************/

use "dta/uk_rd_dataset.dta", clear

keep if district != "हरिद्वार"

local outcome zndays

/*******
Labels
*******/
local lab2015 "a.   Post-Election" "Test for Self-Dealing"
local lab2013 "b.   Pre-Election" "Placebo"






foreach year in 2013 2015 {
	local out `outcome'`year'

	preserve
	
	#d;
	ajayrd `out' rvlev, bw(${bw}) xtitle("Vote Margin (Number of Votes)", size(vlarge)) ytitle("Days of Labor (`year')", size(vlarge))
			name(g`year') title("`lab`year''", size(huge) ) nooffset
			discpos(60 -12) estpos(60 -4) binsize(1) cluster(pid)
			ylabel(0(15)75) xlabel(-16(8)16)
			;
	#d cr
	

	restore
}


graph combine g2015 g2013 , graphregion( color(white) fcolor(white) lcolor(white)) xsize(8)
graph drop g2013 g2015

graph export "ukresults/graphs/mainresult.pdf", replace



/************************************************************************
*************************************************************************
Table 2
*************************************************************************
************************************************************************/

use "dta/uk_rd_dataset.dta", clear


keep if district != "हरिद्वार"

/***********
Define cross-cuts
************/
gen fem 	= regexm(reseng,"Women")						if !mi(reseng)
gen caste 	= !(reseng=="Unreserved" | reseng=="Women")		if !mi(reseng)



/***********
Regressions
************/
gen pos = rvlev > 0 if rvlev < .
egen zndays1516 = rowmean(zndays2015 zndays2016)

eststo clear
local out zndays2015
foreach int of varlist fem caste {
	gen interaction = `int'
	  reg `out' c.pos##c.rvlev##c.interaction if abs(rvlev) < ${bw}, cluster(pid)
	estadd scalar conmean = _b[_cons]
	eststo
	drop interaction
		
}


#d;
esttab using "ukresults/regressions/reservation.tex",  replace
		b(3) se(3)  star(${stars})  noobs 
		sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote 
		sfmt("%9.3f" "%9.0g" "%9.0g")  keep(pos c.pos#c.interaction) order(pos c.pos#c.interaction)
		varlabel(pos "RD Estimate" c.pos#c.interaction "RD Estimate (Interaction)"  ) 
		mtitles(
			"Female Reservation"
			"Caste Reservation"
			)
			
	;
#d cr




/************************************************************************
*************************************************************************
Table 3
*************************************************************************
************************************************************************/



/************************************************************************
Panel A
*************************************************************************/

use "dta/uk_rd_dataset.dta", clear
gen pos = rvlev > 0

//For restriction to two-candidate matches
duplicates tag pid, gen(dup)
gen twomatch = dup ==1

//For restriction to large panchayats
egen tag = tag(pid)
sum aggnvotes if tag & abs(rvlev) < ${bw}, detail
gen large = aggnvotes >= r(p50)

//For any jobs specification
gen anyjob2015 = zndays2015 > 0

//For SUTVA test
gen sutva2015 		= zndays2015
replace sutva2015 	= avg_zndays2015 if rank == 1


local spec1	reg zndays2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
local spec2	reg zndays2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw} 	& twomatch==1	, cluster(pid)			
local spec3	reg zndays2015 		c.rv##c.pos 	if abs(rv) < 0.024 						, cluster(pid)	
local spec4	reg sutva2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw} 					, cluster(pid)		
local spec5	reg znjobs2015 		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
local spec6	reg anyjob2015		c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)
local spec7	reg ztotearn2015 	c.rvlev##c.pos 	if abs(rvlev) < ${bw}					, cluster(pid)	


eststo clear
forvalues i=1/7 {
	`spec`i''
	estadd scalar conmean = _b[_cons]
	eststo

}

#d;
esttab, b(3) se(3)  star(${stars})  noobs 
		sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote 
		sfmt("%9.2f" "%9.0g" "%9.0g")  keep(pos) 
		varlabel(pos "RD Estimate" ) 
		mtitles(
			"Main Spec."
			"Dual Matches"
			"Vote Share as RV"
			"Test: SUTVA"
			"# of Jobs"
			"Any Job?"
			"NREGA Payments"
			)
			
	;
	
esttab using "ukresults/regressions/main.tex", b(3) se(3)  star(${stars})  noobs 
		sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote replace
		sfmt("%9.2f" "%9.0g" "%9.0g")  keep(pos) width(1.0\textwidth)
		varlabel(pos "RD Estimate" ) 
		mgroups("Days of Labor" "Other Outcomes" ,
		pattern(1 0 0 0 1 0 0 ) prefix(\multicolumn{@span}{c}{) suffix(})   
        span erepeat(\cmidrule(lr){@span})) 
		mtitles(
			"Basic"
			"Dual Matches"
			"Vote Share as RV"
			"Test: SUTVA"
			"\# of Jobs"
			"Any Job?"
			"NREGS Payments"
			)
			
	;
#d cr	






/************************************************************************
Panel B
************************************************************************/
eststo clear




/******************
Standard pre-determined outcomes
***********************/

use "dta/uk_rd_dataset_alldetails.dta", clear

//Length of candidate's name
gen namelen = ustrlen(name)
gen mnamelen = ustrlen(malename)


//SCT status
gen sct = category == "SC" | category == "ST" if !mi(category)

//Gender
gen female = gender_candidate == "Female"


gen pos = rvlev > 0


foreach var of varlist zndays2013 sct female det_age /*det_hhsize*/ namelen mnamelen   {
	reg `var' c.rvlev##c.pos if abs(rvlev) < ${bw}, cluster(pid)
	estadd scalar conmean = _b[_cons]
	eststo

}

		
/**************
Match rate
****************/


use "dta/uk_job_matched_2014_sample.dta", clear

//These are cases where the person's name appears in both Devnagari and Roman letters
duplicates tag jobcardno, gen(dup)
list name_hhmem if dup
egen tag = tag(jobcardno)
keep if tag
drop tag dup

//These are cases where we're not sure which of several potential matches is the real match; we'll discard
duplicates report pid match_runup
duplicates tag pid match_runup, gen(dup)
drop if dup
drop dup

//Make it easier to merge with election results
gen rank = (match_winner=="x") + 2*(match_runup=="x")

keep pid jobcardno rank

merge 1:1 pid rank using "dta/ukelect_rv.dta"


gen success = _m == 3
label var success	"Matched Candidate"

keep if abs(rv)<.075

gen rvlev = isrank1*margin - isrank2*margin
gen pos = rvlev > 0



keep if district != "हरिद्वार"

reg success c.rvlev##c.pos if abs(rvlev) < ${bw}, cluster(pid)
estadd scalar conmean = _b[_cons]
eststo

/*******
Table
********/

#d;
esttab, b(3) se(3)  star(${stars})  noobs 
		sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote 
		sfmt("%9.2f" "%9.0g" "%9.0g")  keep(pos) 
		varlabel(pos "RD Estimate" ) 
		mtitles(
			"Days of Labor (2013)"
			"SCT"
			"Female"
			"Age"
			/*"HH Size"*/
			"Cand. Name Len"
			"Rel. Name Len"
			"Matched Candidate"
			)
			
	;
esttab using "ukresults/regressions/placebo.tex", b(3) se(3)  star(${stars})  noobs 
		sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote replace
		sfmt("%9.2f" "%9.0g" "%9.0g")  keep(pos) width(1.1\textwidth)
		varlabel(pos "RD Estimate" ) 
		mtitles(
			"Days of Labor (2013)"
			"SCT"
			"Female"
			"Age"
			/*"HH Size"*/
			"Cand. Name Len"
			"Rel. Name Len"
			"Matched Candidate"
			)
			
	;
#d cr	




/************************************************************************
Panel C
*************************************************************************/



use "dta/uk_rd_dataset.dta", clear


local rv rvlev
local outcome zndays

local bwlist
eststo clear
foreach year in 2015 {
	local out `outcome'`year'
		
		
	
	foreach bw of numlist 25(-2.5)7.5 {
		local tmp = string(`bw', "%9.0g")
		local bwlist `bwlist' `tmp'
		
		preserve
		
		keep if district != "हरिद्वार"
		
		keep if abs(`rv') <= `bw'

		gen pos = `rv' > 0
		drop if `rv' == 0

		
		reg  `out' c.pos##c.`rv' , cluster(pid)
		estadd scalar conmean = _b[_cons]
		eststo


		restore
	}
	

}


#d;
esttab, b(3) se(3)  star(${stars})  noobs 
		sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote 
		sfmt("%9.2f" "%9.0g" "%9.0g")  keep(pos) 
		varlabel(pos "RD Estimate" ) 
			mtitles(
			"$ h=25$ "
			"$ h=22.5$ "
			"$ h=20"
			"$ h=17.5"
			"$ h=15"
			"$ h=12.5"
			"$ h=10"
			"$ h=7.5"
			)
			
	;

	esttab using "ukresults/regressions/bandwidth.tex", b(3) se(3)  star(${stars})  noobs replace
			sca("conmean Outcome at Disc." "N Observations" "N_clust Panchayats") nonote 
			sfmt("%9.2f" "%9.0g" "%9.0g")  keep(pos)  width(1.1\textwidth)
			varlabel(pos "RD Estimate" ) 
			mtitles(
			"$ h=25$ "
			"$ h=22.5$ "
			"$ h=20$ "
			"$ h=17.5$ "
			"$ h=15$ "
			"$ h=12.5$ "
			"$ h=10$ "
			"$ h=7.5$ "
			)
				
		;
#d cr	





/************************************************************************
*************************************************************************
Figure 4
*************************************************************************
************************************************************************/


/************************************************************************
Corruption
************************************************************************/
local lab0 "a.   Cafe Far Away (>5km)"
local lab1 "b.   Cafe Nearby (<5km)"


use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

keep if district != "हरिद्वार"


gen cafe = cen_cybercaf_dist < 1 if cen_cybercaf_dist < .


keep pid rank rvlev zndays*_rescrape cafe
rename *_rescrape *
reshape long zndays, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
drop IND3

keep if abs(rvlev) < ${bw}

foreach cafe in 0 1 {
	preserve 
		
	keep if cafe == `cafe'

	gen pos 		= rvlev > 0 if !mi(rvlev)
	gen rvlevXpos 	= rvlev*pos

	reg zndays IND* rvlev rvlevXpos pos  (c.IND*)#c.(rvlev rvlevXpos pos ), clust(pid)

	clear


	set obs 8
	gen year 	= 2010 + _n
	gen b	 	= .
	gen se		= .

	foreach i of numlist 1/2 4/8 {
		
		replace b 	= _b[c.IND`i'#c.pos] 	if _n == `i'
		replace se 	= _se[c.IND`i'#c.pos] 	if _n == `i'
	}

	replace b		= 0						if _n == 3
	replace se		= 0						if _n == 3
	
	gen bu			= b + se*invttail(e(df_r),.025)
	gen bl			= b - se*invttail(e(df_r),.025)
	
	gen bu2			= b + se*invttail(e(df_r),.05)
	gen bl2			= b - se*invttail(e(df_r),.05)

	gen btxt		= b 			if year == 2014
	gen btxtlb		= "Estimate"
	
	gen bl2txt		= (b+bl2)/2.1  	if year == 2014
	gen bl2txtlb	= "90% CI"
	
	gen bltxt		= bl  			if year == 2014
	gen bltxtlb		= "95% CI"
	
	local textlab1 text(-55 2017 "Direct Routing" "Requirement", color(midblue) )
	local legendtxt0 (scatter btxt year, ms(i) mlabel(btxtlb) mlabcolor(black) mlabsize(medium) ) (scatter bl2txt year, ms(i) mlabel(bl2txtlb) mlabcolor(gs8) mlabsize(medium) ) (scatter bltxt year, ms(i) mlabel(bltxtlb) mlabcolor(gs12) mlabsize(medium) )
	local eltext0	text(65 2014 "Election", color(red) size(large) )
	
	#d;
	twoway (rspike bu bl year, lc(gs14) lw(medthick) ) (rspike bu2 bl2 year, lc(gs8)) (scatter b year, mc(black) ms(s) mlw(none) )
		
		(scatteri 70 2016 70 2018, recast(area) color(ltblue%20) )
		(scatteri -65 2016 -65 2018, recast(area) color(ltblue%20) )
		
		`legend`cafe'' `legendtxt`cafe''
	, 
	xline(2014, lp(dot) lc(red) ) legend(off) `textlab`cafe'' `eltext`cafe''
	 yline(0, lc(black) ) name(g`cafe') ylabel(-60(30)60) yscale( range(-65 70) ) title("`lab`cafe''")
	graphregion(color(white)) xtitle("Year of Labor Allocation", size(large)) ytitle("RD Estimate (Days of Labor)", size(large))
	
	;
	#d cr

	restore
}

graph combine g0 g1, graphregion(color(white) fcolor(white)) xsize(8)
graph drop g0 g1

graph export "ukresults/graphs/dynamic_cyber_new.pdf", replace




/************************************************************************
Mean of non-candidate allocations [for comparison]
************************************************************************/
local lab0 "a.   Cafe Far Away (>5km)"
local lab1 "b.   Cafe Nearby (<5km)"


use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

keep if district != "हरिद्वार"


gen cafe = cen_cybercaf_dist < 1 if cen_cybercaf_dist < .


keep pid rank rvlev zndays*_rescrape avg_zndays*_rescrape cafe
rename *_rescrape *
reshape long zndays avg_zndays, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
//drop IND3

keep if abs(rvlev) < ${bw}

foreach cafe in 0 1 {
	preserve 
		
	keep if cafe == `cafe'

	gen pos 		= rvlev > 0 if !mi(rvlev)
	gen rvlevXpos 	= rvlev*pos

	reg avg_zndays IND* if pos==1, clust(pid) noconstant

	clear


	set obs 8
	gen year 	= 2010 + _n
	gen b	 	= .
	gen se		= .

	foreach i of numlist 1/8 {
		
		replace b 	= _b[IND`i'] 	if _n == `i'
		replace se 	= _se[IND`i'] 	if _n == `i'
	}
	
	gen bu			= b + se*invttail(e(df_r),.025)
	gen bl			= b - se*invttail(e(df_r),.025)
	
	gen bu2			= b + se*invttail(e(df_r),.05)
	gen bl2			= b - se*invttail(e(df_r),.05)


	#d;
	twoway (rspike bu bl year, lc(gs14) lw(medthick) ) (rspike bu2 bl2 year, lc(gs8)) (scatter b year, mc(black) ms(s) mlw(none) )
		
		(scatteri 40 2016 40 2018, recast(area) color(ltblue%20) )
		(scatteri 0 2016 0 2018, recast(area) color(ltblue%20) )

	, 
	xline(2014, lp(dot) lc(red) ) legend(off) 
	graphregion(color(white)) xtitle("Year of Labor Allocation", size(large)) ytitle("Average Days of Labor for Non-Candidates", size(large)) 
	yline(0, lc(black) ) name(g`cafe') ylabel(0(20)40) title("`lab`cafe''")
	
	;
	#d cr
	

	
	restore
}

graph combine g0 g1, graphregion(color(white) fcolor(white)) xsize(8)
graph drop g0 g1

graph export "ukresults/graphs/dynamic_cyber_means_new.pdf", replace





/************************************************************************
*************************************************************************
Figure 5
*************************************************************************
************************************************************************/


/************************************************************************
Corruption
************************************************************************/
cap graph drop _all

use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

keep if district != "हरिद्वार"


gen cafe = cen_cybercaf_dist < 1 if cen_cybercaf_dist < .


keep pid rank rvlev zndays*_rescrape cafe
rename *_rescrape *
reshape long zndays, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
drop IND3

keep if abs(rvlev) < ${bw}


preserve 
		

	gen pos 		= rvlev > 0 if !mi(rvlev)
	gen rvlevXpos 	= rvlev*pos

	reg zndays c.cafe##c.(IND* rvlev rvlevXpos pos  (c.IND*)#c.(rvlev rvlevXpos pos )), clust(pid)

	clear


	set obs 8
	gen year 	= 2010 + _n
	gen b	 	= .
	gen se		= .

	foreach i of numlist 1/2 4/8 {
		
		replace b 	= _b[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
		replace se 	= _se[c.cafe#c.IND`i'#c.pos] 	if _n == `i'
	}

	replace b		= 0						if _n == 3
	replace se		= 0						if _n == 3

	gen bu = b + invttail(e(df_r),.025)*se
	gen bl = b - invttail(e(df_r),.025)*se
	
	gen bu2 = b + invttail(e(df_r),.05)*se
	gen bl2 = b - invttail(e(df_r),.05)*se
	#d;
	twoway
		(rspike bu bl year, lc(purple%25) ) 
		(rspike bu2 bl2 year, lc(purple%50) ) 
		(scatter b year, mc(purple) ) 
		(scatteri 25 2016 25 2018, recast(area) color(ltblue%20) )
		(scatteri -125 2016 -125 2018, recast(area) color(ltblue%20) )
		,
			xline(2014, lp(dot) lc(red) ) text(-115 2014 "Election", color(red) ) 
			text(-110 2017 "Direct Routing" "Requirement", color(midblue) )
			graphregion(color(white) margin(b=-5) ) xtitle("") xscale(off) ytitle("Dif-in-Disc Estimate" "in GPs with Cafes vs. Without") 
			yline(0, lc(black) )   ylabel(-100(25)25) legend(off) name(g0)
			text(-75 2011 "a.   Self-dealing" "(Excess Labor for President)", color(purple) placement(6) ) yscale(range(-125 25))
	;
	#d cr
restore



/************************************************************************
Mean of non-candidate allocations [for comparison]
************************************************************************/
 
use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

keep if district != "हरिद्वार"

bysort pid: keep if _N == 2

gen cafe = cen_cybercaf_dist < 1 if cen_cybercaf_dist < .


keep pid rank rvlev zndays*_rescrape avg_zndays*_rescrape cafe
rename *_rescrape *
reshape long zndays avg_zndays, i(pid rank) j(year)
drop if year == 2019
keep if year >= 2011

tab year, gen(IND)
drop IND3

keep if abs(rvlev) < ${bw}

	 

gen pos 		= rvlev > 0 if !mi(rvlev)
gen rvlevXpos 	= rvlev*pos

reg avg_zndays c.cafe##c.(IND*) if pos==1, clust(pid) 

clear


set obs 8
gen year 	= 2010 + _n
gen b	 	= .
gen se		= .

foreach i of numlist 1/2 4/8 {
	
	replace b 	= _b[c.cafe#c.IND`i'] 	if _n == `i'
	replace se 	= _se[c.cafe#c.IND`i'] 	if _n == `i'
}



replace b		= 0						if _n == 3
replace se		= 0						if _n == 3

gen bu = b + invttail(e(df_r),.025)*se
gen bl = b - invttail(e(df_r),.025)*se

gen bu2 = b + invttail(e(df_r),.05)*se
gen bl2 = b - invttail(e(df_r),.05)*se
#d;
twoway
	(rspike bu bl year, lc(green%25) ) 
	(rspike bu2 bl2 year, lc(green%50) ) 
	(scatter b year, mc(green) ) 
	(scatteri 15 2016 15 2018, recast(area) color(ltblue%20) )
	(scatteri -5 2016 -5 2018, recast(area) color(ltblue%20) )
	,
		xline(2014, lp(dot) lc(red) )
		graphregion(color(white)  ) xtitle("Year of Labor Allocation" ) ytitle("Dif-in-Dif Estimate" "in GPs with Cafes vs. Without") 
		yline(0, lc(black) )    legend(off) name(g1) 
		text(15 2011 "b.   Performance" "(Average Allocation to GP)", color(green) placement(6) ) yscale( range(-5 15) )
;
#d cr

graph combine g0 g1, graphregion(color(white) fcolor(white)) rows(2) imargin(0 0 0 -4)  
graph drop g0 g1



graph export "ukresults/graphs/difindisc_timeplot.pdf", replace












/************************************************************************
************************************************************************
Tables 4 and 5
************************************************************************
************************************************************************/

//We'll use two different definitions of distance
local threshold1 5km
local threshold2 10km
foreach cutoff in 1  {
	use "dta/uk_rd_dataset_alldetails_rescrape.dta", clear

	foreach type in cybercaf postoff majorroad bank market {
		gen `type' = cen_`type'_dist < `cutoff' if cen_`type'_dist < .
	}
	
	gen towndist = cen_pc01_vd_dist_town 
	gen hqdist = cen_hqdist_district 
	gen scfrac = cen_pc11_pca_p_sc/cen_pc11_pca_tot_p
	gen totpop = cen_pc11_pca_tot_p
	gen nschools = cen_nschools
	
	
	egen bid2 = group(district block)


	label var cybercaf	"Near Cyber Cafe"
	label var postoff	"Near Post Office"
	label var majorroad	"Near Major Road"
	label var bank		"Near Bank"
	label var market	"Near Market"
	
	label var towndist "Dist. to town"
	label var hqdist "Dist. to HQ"
	label var scfrac "SC Frac."
	label var totpop "Tot. Pop"
	label var nschools "Primary Schools"
	
	keep if district != "हरिद्वार"
	gen pos = rvlev > 0 if !mi(rvlev)

	gen zndif = zndays2018_rescrape-zndays2015_rescrape



	eststo clear
	
	reg zndif 		c.rvlev##c.pos if abs(rvlev) < ${bw} , cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo
	
	reg zndif 		c.rvlev##c.pos if abs(rvlev) < ${bw} & !mi(cybercaf)	, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo

	reg zndif 		c.rvlev##c.pos##c.cybercaf if abs(rvlev) < ${bw}					, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo

	local keeplist  pos c.pos#c.cybercaf
	local vlabels pos "RD Est."
	local vlabels `vlabels' c.pos#c.cybercaf "RD Est. X Near Cyber Cafe"
	foreach var of varlist postoff majorroad bank market {
		reg zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.`var' c.pos#c.`var' c.rvlev#c.pos#c.`var'	if abs(rvlev) < ${bw}					, cluster(pid) 
		estadd scalar conmean = _b[_cons]
		eststo
		
		local keeplist  `keeplist' c.pos#c.`var'
		local labtmp: var label `var'
		local vlabels `vlabels' c.pos#c.`var' "RD Est. X `labtmp'"
	}
	
	
	//All variables specification
	local var postoff majorroad bank market
	reg zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.(`var') c.pos#c.(`var') c.rvlev#c.pos#c.(`var')	if abs(rvlev) < ${bw}					, cluster(pid) 
	estadd scalar conmean = _b[_cons]
	eststo


	#d;
	esttab, b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
	;
	#d cr


	#d;
	esttab using "ukresults/regressions/cafe_horserace_by_within_`threshold`cutoff''.tex", b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Panchayats") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
			
			replace
	;
	#d cr
	
	
	eststo clear
	reghdfe zndif 		c.rvlev##c.pos##c.cybercaf if abs(rvlev) < ${bw}					, cluster(pid) absorb(bid)
	estadd scalar conmean = _b[_cons]
	estadd local bfe			= "X"
	eststo

	local keeplist  pos c.pos#c.cybercaf
	local vlabels pos "RD Est."
	local vlabels `vlabels' c.pos#c.cybercaf "RD Est. X Near Cyber Cafe"
	foreach var of varlist towndist hqdist scfrac totpop nschools {
		reg zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.`var' c.pos#c.`var' c.rvlev#c.pos#c.`var'	if abs(rvlev) < ${bw}					, cluster(pid)
		estadd scalar conmean = _b[_cons]
		eststo
		
		local keeplist  `keeplist' c.pos#c.`var'
		local labtmp: var label `var'
		local vlabels `vlabels' c.pos#c.`var' "RD Est. X `labtmp'"
	}
	
	//All variables specification
	local var towndist hqdist scfrac totpop nschools 
	reghdfe zndif 		c.rvlev##c.pos##c.cybercaf `var' c.rvlev#c.(`var') c.pos#c.(`var') c.rvlev#c.pos#c.(`var')	if abs(rvlev) < ${bw}					, cluster(pid) absorb(bid2)
	estadd scalar conmean = _b[_cons]
	estadd local bfe			= "X"
	eststo




	#d;
	esttab, b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters" "bfe Block FEs") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
	;
	#d cr
	
	

	#d;
	esttab using "ukresults/regressions/cafe_horserace2_by_within_`threshold`cutoff''.tex", b(3) se(3)  star(${stars})  noobs label
			sca("N Observations" "N_clust Clusters" "bfe Block FEs") nonote 
			sfmt("%9.0g" "%9.0g")  
			keep(`keeplist') varlabels(`vlabels')
				
				mgroups(
			"Change in NREGS Allocation, 2015 to 2018",
			pattern(1 0 0 0 0 0 0) prefix(\multicolumn{@span}{c}{) suffix(})   
			span erepeat(\cmidrule(lr){@span})
			) 
			
			nomtitles
			
			replace
	;
	#d cr
}

